<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/2/11 17:41
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

class Admin_Model extends CI_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取管理员信息
     * @param array $ids
     * @return array
     */
    public function getAdminsByIds(Array $ids)
    {
        if (empty($ids)) {
            return [];
        }
        $db = clone($this->db);
        $db->where_in('id', $ids);
        $query = $db->get('admin');
        $rows = $query->result_array();
        $data = [];
        if (!empty($rows)) foreach($rows as $item) {
            $data[$item['id']] = $item['nickName'];
        }
        return $data;
    }

    /**
     * 检查管理员是否存在
     * @param string $email
     * @return  mixed
     */
    public function checkExists($email = '')
    {
        if (empty($email)) {
            return false;
        }

        $this->db->where('email', $email);
        $query = $this->db->get('admin');
        $row = $query->row_array();
        if (empty($row)) {
            return false;
        }
        return $row;
    }

    /**
     * 添加管理员
     * @param $params
     */
    public function addItem($params, $baseInfo)
    {
        $pass = encryptPassword($params['password']);
        $data = [
            'baseId' => $baseInfo['id'],
            'roleId' => 1,
            'email' => value($params, 'email'),
            'password' => $pass['password'],
            'salt' => $pass['salt'],
            'nickName' => value($params, 'charger'),
            'created' => date('Y-m-d H:i:s'),
            'lastTime' => date('Y-m-d H:i:s'),
            'lastIp' => remoteAddr(),
            'isShow' => 0,
            'status' => 1
        ];

        $db1 = clone($this->db);
        $db1->insert('admin', $data);
        $id = $db1->insert_id();
        $profile = [
            'adminId' => $id,
            'path' => '',
            'avatar' => '',
            'phone' => $params['phone']
        ];

        $db2 = clone($this->db);
        $db2->insert('admin_profile', $profile);
        return true;
    }

    /**
     * 改密码
     */
    public function modPass($userId, $pass, $salt)
    {
        if (empty($pass) || empty($salt)) {
            return false;
        }

        $this->db->where('id', $userId);
        $this->db->update('admin', [
            'password' => $pass,
            'salt' => $salt
        ]);

        return true;
    }

    /**
     * 是否有管理员存在
     * @param $roleId
     * @return mixed
     */
    public function check($roleId)
    {
        $q = $this->db->where('roleId', $roleId)->get('admin');
        return $q->result_array();
    }

    /**
     * 删除
     * @param $roleId
     * @return mixed
     */
    public function remove($roleId)
    {
        return $this->db->where('id', $roleId)->delete('admin_role');
    }
}
